package com.caiheng.api.service.estate.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.caiheng.api.dao.estate.EstateRoomBangUserMapper;
import com.caiheng.api.dao.estate.EstateRoomMapper;
import com.caiheng.api.dao.wxuser.UserMapper;
import com.caiheng.api.entity.estate.EstateRoom;
import com.caiheng.api.entity.estate.EstateRoomBangUser;
import com.caiheng.api.entity.dto.EstateRoomDto;
import com.caiheng.api.entity.wxuser.User;
import com.caiheng.api.exception.TransactionalException;
import com.caiheng.api.service.estate.EstateRoomService;
import com.caiheng.api.service.base.impl.BaseServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 小区内的房屋列信息Service业务层处理
 *
 * @author ruoyi
 * @date 2022-06-28
 */
@Service
public class EstateRoomServiceImpl extends BaseServiceImpl<EstateRoomMapper, EstateRoom> implements EstateRoomService {

    @Resource
    private EstateRoomMapper estateRoomMapper;
    @Resource
    private EstateRoomBangUserMapper roomBangUserMapper;
    @Resource
    private UserMapper userMapper;

    @Override
    @Transactional
    public int bandRoomByPhoneNum(int userId, int estateId, String phoneNum, User user) {
        int ret = 0;
        try{
            QueryWrapper<EstateRoom> qw = new QueryWrapper<>();
            qw.eq("estate_id",estateId);
            qw.like("phone_num",phoneNum);
            List<EstateRoom> rooms = estateRoomMapper.selectList(qw);
            if(CollUtil.isNotEmpty(rooms)) {
                for (EstateRoom room : rooms){
                    QueryWrapper<EstateRoomBangUser> qwBangUser = new QueryWrapper<>();
                    qwBangUser.eq("estate_id",estateId);
                    qwBangUser.eq("bang_wx_user_id",userId);
                    qwBangUser.eq("room_id",room.getId());
                    EstateRoomBangUser bangUser = roomBangUserMapper.selectOne(qwBangUser);
                    if(bangUser == null){
                        bangUser = new EstateRoomBangUser();
                        bangUser.setBangWxUserId(userId);
                        bangUser.setEstateId(estateId);
                        bangUser.setRoomId(room.getId());
                        ret = roomBangUserMapper.insert(bangUser);
                        if(ret <= 0){
                            throw new TransactionalException("roomBangUserMapper insert error");
                        }
                    }

                    room.setBangWxUserId(userId);
                    ret = estateRoomMapper.updateById(room);
                    if(ret <= 0){
                        throw new TransactionalException("estateRoomMapper insert error");
                    }
                }



                if(user.getEstateId() == null || user.getEstateId() == 0){
                    user.setEstateId(estateId);
                    ret = userMapper.updateById(user);
                    if(ret <= 0){
                        throw new TransactionalException("userMapper updateById error");
                    }
                }
            }
            ret = 1;
        }catch (Exception e){
            e.printStackTrace();
            throw new TransactionalException("estateRoomMapper insert error");
        }
        return ret;
    }

    @Override
    public long getUnBandRoom(int userId, int estateId, String phoneNum) {
        long count = 0;
        QueryWrapper<EstateRoom> qw = new QueryWrapper<>();
        qw.eq("estate_id",estateId);
        qw.like("phone_num",phoneNum);
        List<EstateRoom> rooms = estateRoomMapper.selectList(qw);
        if(CollUtil.isNotEmpty(rooms)) {
            for (EstateRoom room : rooms) {
                QueryWrapper<EstateRoomBangUser> qwBangUser = new QueryWrapper<>();
                qwBangUser.eq("estate_id", estateId);
                qwBangUser.eq("bang_wx_user_id", userId);
                qwBangUser.eq("room_id", room.getId());
                EstateRoomBangUser bangUser = roomBangUserMapper.selectOne(qwBangUser);
                if (bangUser == null) {
                    count++;
                }
            }
        }
        return count;
    }


    @Override
    @Transactional
    public int bandRoomByNoPhone(int userId, int estateId, int roomId) {
        int ret = 0;
        try{
            QueryWrapper<EstateRoomBangUser> qwBangUser = new QueryWrapper<>();
            qwBangUser.eq("estate_id",estateId);
            qwBangUser.eq("bang_wx_user_id",userId);
            qwBangUser.eq("room_id",roomId);
            qwBangUser.last("limit 1");
            EstateRoomBangUser bangUser = roomBangUserMapper.selectOne(qwBangUser);
            if(bangUser == null){
                bangUser = new EstateRoomBangUser();
                bangUser.setBangWxUserId(userId);
                bangUser.setEstateId(estateId);
                bangUser.setRoomId(roomId);
                ret = roomBangUserMapper.insert(bangUser);
                if(ret <= 0){
                    throw new TransactionalException("roomBangUserMapper insert error");
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            throw new TransactionalException("estateRoomMapper insert error");
        }
        return ret;
    }

    @Override
    public long myRoomCountByEstateId(int userId, int estateId) {
        QueryWrapper<EstateRoomBangUser> qw = new QueryWrapper<>();
        if(estateId > 0){
            qw.eq("estate_id", estateId);
        }
        qw.eq("bang_wx_user_id", userId);
        return roomBangUserMapper.selectCount(qw);
    }


    @Override
    public List<EstateRoom> getRoomListByUserId(int userId,String keyword) {
        return estateRoomMapper.getRoomListByUserId(userId,keyword);
    }

    @Override
    public List<EstateRoomDto> getEstateRoomList(int estateId) {
        List<EstateRoomDto> list = new ArrayList<>();
        QueryWrapper<EstateRoom> qw = new QueryWrapper<>();
        qw.eq("estate_id",estateId);
        qw.groupBy("build_no");
        List<EstateRoom> estateRooms = estateRoomMapper.selectList(qw);
        int indexBuild = 0;
        for (EstateRoom estateRoom : estateRooms){
            EstateRoomDto build = new EstateRoomDto();
            build.setName(estateRoom.getBuildNo());
            build.setText(estateRoom.getBuildNo()+"号楼");
            build.setEstateId(estateRoom.getEstateId());
            build.setLevel(1);
            build.setIndex(indexBuild);

            int indexUnit = 0;
            List<EstateRoomDto> unitChilds = new ArrayList<>();
            QueryWrapper<EstateRoom> qwUnit = new QueryWrapper<>();
            qwUnit.eq("estate_id",estateId);
            qwUnit.eq("build_no",estateRoom.getBuildNo());
            qwUnit.groupBy("unit_no");
            List<EstateRoom> units = estateRoomMapper.selectList(qwUnit);
            for (EstateRoom unit : units){
                EstateRoomDto unitChild = new EstateRoomDto();
                unitChild.setName(unit.getUnitNo());
                unitChild.setText(unit.getUnitNo()+"单元");
                unitChild.setEstateId(unit.getEstateId());
                unitChild.setLevel(2);
                unitChild.setIndex(indexUnit);

                int indexRoom = 0;
                List<EstateRoomDto> roomChilds = new ArrayList<>();
                QueryWrapper<EstateRoom> qwRoom = new QueryWrapper<>();
                qwRoom.eq("estate_id",estateId);
                qwRoom.eq("build_no",unit.getBuildNo());
                qwRoom.eq("unit_no",unit.getUnitNo());
                qwRoom.groupBy("room_no");
                List<EstateRoom> rooms = estateRoomMapper.selectList(qwRoom);
                for (EstateRoom room : rooms){
                    EstateRoomDto roomChild = new EstateRoomDto();
                    roomChild.setName(room.getRoomNum());
                    roomChild.setText(room.getRoomNum());
                    roomChild.setEstateId(room.getEstateId());
                    roomChild.setLevel(3);
                    roomChild.setIndex(indexRoom);
                    roomChild.setRoomId(room.getId());

                    roomChilds.add(roomChild);
                    indexRoom++;
                }
                indexUnit++;
                unitChild.setValues(roomChilds);
                unitChilds.add(unitChild);
            }
            indexBuild++;
            build.setValues(unitChilds);
            list.add(build);
        }
        return list;
    }

    @Override
    public EstateRoom getMyRoomByRoomId(int userId, int estateId, int roomId) {
        return null;
    }
}
